package com.vmj.heap;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by yangshoujun on 2017/9/9 上午10:51.
 */
public class ClassUtils {

    public static Map<String, String> primitiveMap = new HashMap<String, String>();

    static {
        primitiveMap.put("void", "V");
        primitiveMap.put("boolean", "Z");
        primitiveMap.put("byte", "B");
        primitiveMap.put("char", "C");
        primitiveMap.put("short", "S");
        primitiveMap.put("int", "I");
        primitiveMap.put("float", "F");
        primitiveMap.put("long", "J");
        primitiveMap.put("double", "D");

    }

    public static String getArrayClassName(String className) {
        return "[" + className;
    }

    public static String toDescriptor(String className) {
        if(className.charAt(0) == '[') {
            return className;
        }

        if(primitiveMap.containsKey(className)) {
            return primitiveMap.get(className);
        }

        return "L" + className + ";";
    }

    public static String toClassName(String descriptor) {
        if(descriptor.charAt(0) == '[') {
            return descriptor;
        } else if(descriptor.charAt(0) == 'L') {
            return descriptor.substring(1, descriptor.length() - 1);
        } else {
            Set<String> keys = primitiveMap.keySet();
            for(String cls : keys) {
                if(primitiveMap.get(cls).equals(descriptor)) {
                    return cls;
                }
            }
        }

        return descriptor;

//        throw new RuntimeException("Invalid descriptor: " + descriptor);
    }

    public static VMObject getSignatureStr(ClassLoader classloader, String signature) {
        if(!"".equals(signature) && signature != null) {
            return StringPool.getStringObject(classloader, signature);
        }
        return null;
    }

    public static VMObject toByteArr(ClassLoader classLoader, byte[] data) {
        if(data != null) {
            return ArrayObject.newByteArray(classLoader, data);
        }
        return null;
    }

    public static VMObject toClassArr(ClassLoader classLoader, VMClass[] classes) {
        if(classes == null) {
            return null;
        }

        int arrLen = classes.length;
        VMClass classArrClass = classLoader.loadClass("java/lang/Class").getArrayClass();
        VMObject classArr = VMObject.newArray(classArrClass, arrLen);
        if(arrLen > 0) {
            VMObject[] classObjs = (VMObject[]) classArr.getData();
            for(int i = 0; i < classes.length;i++) {
                classObjs[i] = classes[i].getjClass();
            }
        }
        return classArr;
    }
}
